﻿using System;
using JigLibX.Collision;
using JigLibX.Geometry;
using JigLibX.Math;
using JigLibX.Physics;
using Microsoft.Xna.Framework;
using SolarWinds.Helpers;
using SolarWinds.Shapes;

namespace SolarWinds.Actors
{
    /// <summary>
    /// Represents a sphereical actor around a shape
    /// </summary>
    class SphereActor : Actor
    {
        private readonly Vector3 mCenterOfMass;

        /// <summary>
        /// Create a sphereical actor. 
        /// Remember that the actor makes use of the bounding sphere of the shape. 
        /// This bounding sphere is created in the LoadContent mehtod of the shape.
        /// So best create the SphereActor at the end of the LoadContent mehtod. 
        /// </summary>
        /// <param name="shape">The shape</param>
        /// <param name="elasticity">Elasticity</param>
        /// <param name="staticRoughness">Static Roughness</param>
        /// <param name="dynamicRoughness">Dynamic Roughness</param>
        /// <param name="mass">Mass of the actor</param>
        public SphereActor(Shape shape, float elasticity, float staticRoughness, float dynamicRoughness, float mass) : 
            base(shape)
        {
            float scale = Math.Max(mShape.Scale.X, Math.Max(mShape.Scale.Y, mShape.Scale.Z));

            var sphere = new Sphere(mShape.BoundingSphere.Center, mShape.BoundingSphere.Radius * scale);
            Skin.AddPrimitive(sphere, new MaterialProperties(elasticity, staticRoughness, dynamicRoughness));

            mCenterOfMass = PhysicsHelper.SetMass(mass, Skin, Body);

            Body.MoveTo(mShape.Position, Matrix.CreateFromQuaternion(mShape.Rotation));
            Skin.ApplyLocalTransform(new Transform(-mCenterOfMass, Matrix.Identity));
            Body.EnableBody();

            PhysicsSystem.CurrentPhysicsSystem.CollisionSystem.AddCollisionSkin(Skin);
        }
    }
}
